<template>
  <el-container>
    <el-main>
      <div class="sa-model-form-wrap">
        <div class="chat-head-wrap" style="height: 40px; width: 100%"></div>

        <div class="sa-flex sa-col-center sa-row-between chat-head">
          <div class="nickname">{{ props.modal.params.nickname }}</div>
          <el-dropdown trigger="click">
            <div class="sa-flex cursor-pointer sa-p-l-8 sa-p-r-8">
              <div class="room-name sa-m-r-4">{{ curRoom?.name }}</div>
              <el-icon><ArrowDown /></el-icon>
            </div>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item
                  v-for="item in roomIdSelect"
                  :key="item.value"
                  @click="changeRoom(item)"
                  >{{ item.name }}</el-dropdown-item
                >
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>

        <!-- 消息列表 -->
        <button
          class="loadmore-btn sa-reset-button"
          v-show="state.chatList.length && pagination.lastPage > 1"
          @click="onLoadMore"
        >
          {{ loadingMap[pagination.loadStatus].title
          }}<i class="loadmore-icon sa-m-l-6" :class="loadingMap[pagination.loadStatus].icon"></i>
        </button>
        <div class="sa-message sa-flex-col" v-if="state.chatList.length">
          <div class="message-list sa-m-b-20" v-for="(item, index) in state.chatList" :key="index">
            <!-- 系统+日期 -->
            <div class="sa-flex sa-col-center sa-row-center">
              <div v-if="item.from == 'system'" class="message-system sa-m-b-20">
                {{ item.content.text }}
              </div>
              <div v-if="showTime(item, index)" class="message-date sa-m-b-20">
                {{ formatTime(item.date) }}
              </div>
            </div>

            <!-- 其他 -->
            <div
              class="sa-flex"
              :class="[
                item.from == 'customer_service'
                  ? `sa-row-right`
                  : item.from == 'customer'
                  ? `sa-row-left`
                  : '',
              ]"
            >
              <!-- 客户头像 -->
              <el-avatar
                v-show="item.from == 'customer'"
                class="chat-avatar customer-avatar"
                style="margin-right: 10px"
                :size="40"
                :src="checkUrl(item?.sender?.avatar)"
              >
                <img src="/static/images/chat/head.png" />
              </el-avatar>

              <div>
                <div>
                  <div
                    v-show="item.from == 'customer_service'"
                    class="chat-nickname"
                    style="text-align: right"
                  >
                    {{ item?.sender?.name }}
                  </div>
                  <div
                    v-show="item.from == 'customer'"
                    class="chat-nickname"
                    style="text-align: left"
                  >
                    {{ item?.sender?.nickname }}
                  </div>
                </div>
                <div
                  :class="[
                    item.from == 'customer_service'
                      ? `message-right`
                      : item.from == 'customer'
                      ? ` message-left`
                      : '',
                    `message-${item.mode}`,
                  ]"
                >
                  <!-- 文本 -->
                  <template v-if="item.mode == 'text'">
                    <div
                      class="message-text"
                      @click="onRichtext"
                      v-html="replaceEmoji(item.content.text)"
                    ></div>
                  </template>

                  <!-- 图片预览 -->
                  <el-image-viewer
                    v-if="showViewer"
                    ref="elImageViewer"
                    @close="onClose"
                    :url-list="viewerUrlList"
                  />

                  <!-- 图片 -->
                  <template v-if="item.mode == 'image'">
                    <el-image
                      class="message-img"
                      fit="cover"
                      :src="item.content.url"
                      :preview-src-list="[item.content.url]"
                      hide-on-click-modal
                    >
                    </el-image>
                  </template>

                  <!-- 商品 -->
                  <template v-if="item.mode == 'goods'">
                    <div class="message-card sa-flex">
                      <sa-image
                        class="sa-m-r-8"
                        :size="40"
                        fit="cover"
                        :url="item.content.item.image"
                      />
                      <div class="">
                        <div class="card-title sa-m-b-8 sa-line-1">
                          {{ item.content.item.title }}
                        </div>
                        <div class="price-text">{{
                          isArray(item.content.item.price)
                            ? item.content.item.price[0]
                            : item.content.item.price
                        }}</div>
                      </div>
                    </div>
                  </template>

                  <!-- 订单 -->
                  <template v-if="item.mode == 'order'">
                    <div class="message-card">
                      <div class="order-sn sa-line-1 sa-m-b-10" v-show="item.content.item.order_sn">
                        订单号:{{ item.content.item.order_sn }}
                      </div>
                      <div
                        class="order-goods sa-flex sa-col-center"
                        v-if="item.content.item.items.length > 0"
                      >
                        <sa-image
                          class="sa-m-r-8"
                          :size="40"
                          fit="cover"
                          :url="item.content.item.items[0].goods_image"
                        />
                        <div class="sa-flex-1">
                          <div class="card-title sa-m-b-8 sa-line-1">
                            {{ item.content.item.items[0].goods_title }}
                          </div>
                          <div class="order-total sa-flex sa-row-between">
                            <span>共{{ item.content.item.items.length }}件商品</span>
                            <span>合计 ¥{{ item.content.item.pay_fee }}</span>
                          </div>
                        </div>
                      </div>
                    </div>
                  </template>
                </div>
              </div>

              <!-- 客服头像 -->
              <el-avatar
                v-show="item.from == 'customer_service'"
                class="chat-avatar customer-avatar"
                style="margin-left: 10px"
                :size="40"
                :src="checkUrl(item?.sender?.avatar)"
              >
                <img src="/static/images/chat/head.png" />
              </el-avatar>
            </div>
          </div>
        </div>

        <div
          class="sa-flex sa-row-center sa-col-center"
          style="width: 100%; height: 100%"
          v-show="!state.chatList.length"
        >
          <el-empty>
            <template #image>
              <sa-svg className="empty-svg" name="sa-kongkongruye" size="150"></sa-svg>
            </template>
            <template #description>
              <div class="empty-description">暂时没有会话哦！</div>
            </template>
          </el-empty>
        </div>
      </div>
    </el-main>
  </el-container>
</template>

<script setup>
  import { onMounted, reactive, ref, unref, computed } from 'vue';

  import chatApi from '@/app/chat/api';
  import { formatMessage } from '../../utils/socket.utils';
  import dayjs from 'dayjs';
  import { checkUrl } from '@/sheep/utils/checkUrlSuffix';
  import sheep from '@/sheep';
  import emojiData from '../../components/chat/emoji.json';
  import { isArray } from 'lodash';

  const props = defineProps({
    modal: {
      type: Object,
    },
  });
  const chatStore = sheep.$store('socket');
  const state = reactive({
    chatList: [],
  });
  const loadingMap = {
    loadmore: {
      title: '查看更多',
      icon: 'el-icon-d-arrow-left',
    },
    nomore: {
      title: '没有更多了',
      icon: '',
    },
    loading: {
      title: '加载中... ',
      icon: 'el-icon-loading',
    },
  };

  // 所属分类选项
  let roomIdSelect = ref([]);
  async function getChatCofig() {
    const { error, data } = await chatApi.chatInit();
    if (error === 0) {
      roomIdSelect.value = data.default_rooms;
    }
  }

  // 图片预览
  const showViewer = ref(false);
  let viewerUrlList = reactive([]);
  // 点击富文本内容
  const onRichtext = (e) => {
    if (e.target.nodeName == 'IMG') {
      showViewer.value = true;
      viewerUrlList = [e.target.currentSrc];
    }
  };
  // 关闭预览
  const onClose = () => {
    showViewer.value = false;
  };

  // 是否显示时间

  const showTime = (item, index) => {
    if (unref(state.chatList)[index + 1]) {
      return unref(state.chatList)[index + 1].date - item.date > 5 * 60 * 1000;
    }
  };

  // 格式化时间
  const formatTime = (time) => {
    let diffTime = new Date().getTime() - time;
    if (diffTime > 28 * 24 * 60 * 1000) {
      return dayjs(time).format('MM/DD HH:mm');
    }
    if (diffTime > 360 * 28 * 24 * 60 * 1000) {
      return dayjs(time).format('YYYY/MM/DD HH:mm');
    }
    return dayjs(time).fromNow();
  };

  function replaceEmoji(data) {
    let newData = data;
    if (typeof newData != 'object') {
      let reg = /\[(.+?)\]/g; // [] 中括号
      let zhEmojiName = newData.match(reg);
      if (zhEmojiName) {
        zhEmojiName.forEach((item) => {
          let emojiFile = selEmojiFile(item);
          newData = newData.replace(
            item,
            `<img class="chat-img" style="width:25px;height:25px;margin:0 3px" src="${checkUrl(
              '/static/img/chat/emoji/' + emojiFile,
            )}"/>`,
          );
        });
      }
    }
    return newData;
  }

  function selEmojiFile(name) {
    for (let index in emojiData) {
      if (emojiData[index].name == name) {
        return emojiData[index].file;
      }
    }
    return false;
  }

  // 获取聊天记录
  const curRoom = computed(() => roomIdSelect.value[0]);
  const pagination = reactive({
    page: 0,
    list_rows: 10,
    last_id: 0,
    lastPage: 0,
    loadStatus: 'loadmore', //loadmore-加载前的状态，loading-加载中的状态，nomore-没有更多的状态
  });
  async function getDetail() {
    pagination.page += 1;
    pagination.loadStatus = 'loading';
    const { data } = await chatApi.admin.user.detailList({
      search: JSON.stringify({
        chat_user_id: unref(props.modal.params.id),
        room_id: curRoom?.value,
      }),
      ...pagination,
    });
    if (isRoom.value) {
      state.chatList = [];
    }
    data.data.forEach((item) => {
      state.chatList.unshift(formatMessage(item));
    });

    pagination.page = data.current_page;
    pagination.lastPage = data.last_page;
    pagination.loadStatus = pagination.page < pagination.lastPage ? 'loadmore' : 'nomore';
    if (pagination.last_id == 0) {
      pagination.last_id = data.data.length > 0 ? data.data[0].id : 0;
    }
    isRoom.value = false;
  }

  // 加载更多
  const onLoadMore = () => {
    pagination.page < pagination.lastPage && getDetail();
  };

  let isRoom = ref(false);

  // 切换room
  const changeRoom = (data) => {
    curRoom.value = data;
    isRoom.value = true;
    pagination.page = 0;
    getDetail();
  };

  onMounted(async () => {
    await getChatCofig();
    getDetail();
  });
</script>
<style lang="scss">
  .message-text {
    div,
    span,
    p {
      white-space: normal;
    }
  }
</style>

<style lang="scss" scoped>
  .sa-model-form-wrap {
    width: 100%;
    padding: 0 var(--sa-padding) 56px;
    background: var(--sa-background-assist);
    border-radius: 8px 8px 0 0;
    overflow: hidden;
    overflow-y: auto;
    height: 100%;
  }
  .chat-head {
    height: 60px;
    width: 100%;
    padding: 0 16px;
    position: absolute;
    top: 40px;
    left: 0;
    border-bottom: 1px solid var(--sa-table-header-bg);
    background: var(--sa-background-assist);
    z-index: 11;
  }

  // 加载更多
  .loadmore-btn {
    width: 100%;
    height: 40px;
    font-size: 12px;
    color: var(--sa-subfont);
    .loadmore-icon {
      transform: rotate(90deg);
    }
  }
  .sa-message {
    // padding: 17px;
    .message-right {
      background: var(--t-bg-active);
      border-radius: 4px 4px 0 4px;
      padding: 12px;
      color: var(--sa-font);
    }
    .message-left {
      background: var(--sa-table-header-bg);
      border-radius: 4px 4px 0 4px;
      padding: 12px;
      align-self: flex-start;
      color: var(--sa-font);
    }
    .message-list {
      // 日期
      .message-date {
        color: var(--sa-subfont);
        font-size: 12px;
      }

      .chat-nickname {
        font-size: 12px;
        font-weight: 400;
        color: var(--sa-font);
        margin-bottom: 4px;
      }

      // 普通文本
      .message-text {
        max-width: 200px;
        font-size: 14px;
        color: var(--sa-font);
        white-space: normal;
        word-break: break-all;
        word-wrap: break-word;
      }

      // 图片
      .message-img {
        width: 100px;
        height: 100px;
        border-radius: 6px;
      }

      // 商品订单
      .message-card {
        width: 240px;
        .order-sn {
          // width: 200px;
          font-size: 12px;
          color: #806af6;
        }
        .card-title {
          width: 180px;
          font-size: 14px;
          color: var(--sa-font);
        }
        .tag-text {
          color: #ff4d4f;
          font-size: 12px;
        }
        .price-text {
          color: #ff4d4f;
          font-size: 12px;
        }
        .order-goods {
          background: var(--sa-background-assist);
          padding: 8px;
        }
        .order-total {
          width: 100%;
          line-height: 14px;
          font-size: 12px;
          font-weight: 400;
          color: var(--sa-font);
        }
      }
    }
  }
</style>
